package ACM.HuaWei;

import java.util.*;

/**
 * @author way
 * @create 2025-04-09 22:24
 */
public class _1 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int N = scanner.nextInt();
        Map<String, String> predecessors = new HashMap<>();
        Set<String> allVersions = new HashSet<>();

        for (int i = 0; i < N; i++) {
            String current = scanner.next();
            String pre = scanner.next();
            predecessors.put(current, pre.equals("NA") ? null : pre);
            allVersions.add(current);
            if (!pre.equals("NA")) {
                allVersions.add(pre);
            }
        }

        Map<String, Integer> depthCache = new HashMap<>();
        int maxDepth = 0;
        List<String> maxVersions = new ArrayList<>();

        for (String version : allVersions) {
            int depth = computeDepth(version, predecessors, depthCache);
            if (depth > maxDepth) {
                maxDepth = depth;
                maxVersions.clear();
                maxVersions.add(version);
            } else if (depth == maxDepth) {
                maxVersions.add(version);
            }
        }

        Collections.sort(maxVersions);
        System.out.println(String.join(" ", maxVersions));
    }

    private static int computeDepth(String version, Map<String, String> predecessors, Map<String, Integer> depthCache) {
        if (depthCache.containsKey(version)) {
            return depthCache.get(version);
        }

        Stack<String> stack = new Stack<>();
        stack.push(version);

        while (!stack.isEmpty()) {
            String current = stack.peek();
            String pre = predecessors.getOrDefault(current, null);

            if (pre == null) {
                depthCache.put(current, 1);
                stack.pop();
            } else if (depthCache.containsKey(pre)) {
                depthCache.put(current, depthCache.get(pre) + 1);
                stack.pop();
            } else {
                stack.push(pre);
            }
        }

        return depthCache.get(version);
    }}
